package com.app.medicalcontrol.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.app.medicalcontrol.R;
import com.app.medicalcontrol.basis.BasisFragment;
import com.app.medicalcontrol.other.PhotoScanActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import butterknife.BindView;
import my.LogUtil;
/**
 * Created by otis on 2018/4/19.
 */
@SuppressLint("ValidFragment")

public class H5Fragment extends BasisFragment {

    @BindView(R.id.webview)
    WebView mWebView;

    private String url;
    private String title;

    public static H5Fragment getInstance(String url) {
        H5Fragment fragment = new H5Fragment();
        fragment.url = url;
        return fragment;
    }

    public static H5Fragment getInstance(String url,String title) {
        H5Fragment fragment = new H5Fragment();
        fragment.url = url;
        fragment.title = title;
        return fragment;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @JavascriptInterface
    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.activity_h5_detail);

        setTitle(title+"");
        setTitleRightButton(R.mipmap.top_icon_msg, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getMessageInfo(v);
            }
        });

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setDisplayZoomControls(false);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setSaveEnabled(true);
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.clearCache(true);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(chromeClient);
        mWebView.requestFocus();
        mWebView.addJavascriptInterface(new MJavascriptInterface(), "imagelistener");
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(mContext);
        ImageLoader.getInstance().init(configuration);

//        getDetail();
        mWebView.loadUrl(url);
    }

//    void getDetail() {
//        showProgress();
//        RequestParams params = new RequestParams();
//        params.put("goods_id", goodsId);
//        showProgress();
//        HttpRestClient.get(Constants.URL_GET_CONTENT, params, new MyHttpListener() {
//                    @Override
//                    public void onSuccess(int httpWhat, Object result) {
//                        GoodsTypeBean bean = (GoodsTypeBean) result;
//                        setView(bean);
//                        dismissProgress();
//                    }
//
//                    @Override
//                    public void onFinish(int httpWhat) {
//
//                    }
//                },
//                0, GoodsTypeBean.class);
//    }
//
//    private void setView(GoodsTypeBean bean) {
//        if (bean == null) return;
//        mWebView.loadDataWithBaseURL(null, bean.getContent(), "text/html", "utf-8", null);
//    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        if (mWebView != null) {
            try {
                mWebView.setWebViewClient(null);
                mWebView.destroy();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

    @SuppressLint("NewApi")
    class MyWebViewClient extends WebViewClient {
        String loginCookie;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            // if(myProgressDialog != null &&
            // !myProgressDialog.isShowing())myProgressDialog.show();
            if (url.startsWith("mailto:") || url.startsWith("geo:")
                    || url.startsWith("tel:") || url.indexOf(".3gp") != -1 || url.indexOf(".mp4") != -1
                    || url.indexOf(".flv") != -1
                    || url.indexOf(".swf") != -1) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else if (url.startsWith("data:")) {
                return true;
            } else if (URLUtil.isNetworkUrl(url)) {
                view.loadUrl(url);
            } else {
                return super.shouldOverrideUrlLoading(view, url);
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            dismissProgress();
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            // CookieManager cookieManager = CookieManager.getInstance();
            // loginCookie = cookieManager.getCookie(url);
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            // CookieManager cookieManager = CookieManager.getInstance();
            // cookieManager.setCookie(url, loginCookie);
            super.onPageFinished(view, url);
            imgReset();
            dismissProgress();
            addImageClickListener(view);
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            if (!mContext.isFinishing()) {
                showProgress();
            }
        }

    }

    private WebChromeClient chromeClient = new WebChromeClient() {

        @Override
        public boolean onJsConfirm(WebView arg0, String arg1, String arg2, JsResult arg3) {
            return super.onJsConfirm(arg0, arg1, arg2, arg3);
        }

        @Override
        public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
            return super.onJsAlert(webView, s, s1, jsResult);
        }

        @Override
        public boolean onJsPrompt(WebView webView, String s, String s1, String s2, JsPromptResult jsPromptResult) {
            return super.onJsPrompt(webView, s, s1, s2, jsPromptResult);
        }


        @Override
        public void onReceivedTitle(WebView arg0, final String arg1) {
            super.onReceivedTitle(arg0, arg1);
//            Log.i("yuanhaizhou", "webpage title is " + arg1);

        }
    };

    private void imgReset() {
        mWebView.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName('img'); "
                + "for(var i=0;i<objs.length;i++)  " + "{"
                + "var img = objs[i];   "
                + "    img.style.width = '100%';   "
                + "    img.style.height = 'auto';   "
                + "}" + "})()");

    }

    private void addImageClickListener(WebView webView) {
        LogUtil.i("addImageClickListener------->");
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistener.openImage(this.src);  " +//通过js代码找到标签为img的代码块，设置点击的监听方法与本地的openImage方法进行连接
                "    }  " +
                "}" +
                "})()");
    }
    public class MJavascriptInterface {

        public MJavascriptInterface() {
        }

        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            LogUtil.i("addImageClickListener------openImage---->" + img);
            PhotoScanActivity.toImgScanActivityt(mContext, img, "");
        }
    }

}



//public class H5Fragment extends BasisFragment implements View.OnClickListener {
//    com.tencent.smtt.sdk.WebView mWebView;
//    String wapurl;
//
//    public static H5Fragment getInstance(String wapurl) {
//        H5Fragment fragment = new H5Fragment();
//        fragment.wapurl = wapurl;
//        return fragment;
//    }
//
//    @Override
//    public void initViews() {
//        // TODO Auto-generated method stub
//        setContentView(R.layout.base_webview_local_x5);
//        super.initViews();
//
//        mWebView = (com.tencent.smtt.sdk.WebView) findViewById(R.id.webview);
//        mWebView.getSettings().setJavaScriptEnabled(true);
//        // mWebView.getSettings().setSupportZoom(true);
//        // mWebView.getSettings().setBuiltInZoomControls(true);
//        mWebView.setInitialScale(20);
//        mWebView.getSettings().setUseWideViewPort(true);
//        mWebView.getSettings().setAppCacheEnabled(true);
//        mWebView.getSettings().setSavePassword(false);
////         mWebView.getSettings().setAppCachePath("external/chromium/net/disk_cache/");
//        // mWebView.getSettings().setDisplayZoomControls(true);
//        mWebView.setScrollBarStyle(com.tencent.smtt.sdk.WebView.SCROLLBARS_INSIDE_OVERLAY);
//        mWebView.setSaveEnabled(true);
//        mWebView.getSettings().setAllowContentAccess(true);
//        mWebView.getSettings().setAllowFileAccess(true);
//        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//        mWebView.getSettings().setPluginState(com.tencent.smtt.sdk.WebSettings.PluginState.ON);
//        mWebView.getSettings().setDomStorageEnabled(true);
//        // setZoomControlGone(mWebView);
////        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        mWebView.clearCache(false);
////		webSet.setRenderPriority(WebSettings.RenderPriority.HIGH);
//        //
//        mWebView.setWebViewClient(new H5Fragment.MyWebViewClient());
////        mWebView.setWebChromeClient(new MyWebChromeClient());
//        mWebView.setWebChromeClient(chromeClient);
//        mWebView.requestFocus();
//    }
//
//    @Override
//    public void initData(Bundle savedInstanceState) {
//        // TODO Auto-generated method stub
//        super.initData(savedInstanceState);
//        initUrl();
//    }
//
//    @Override
//    public void onDestroyView() {
//        if (mWebView != null) {
//            try {
//                mWebView.setWebViewClient(null);
//                mWebView.destroy();
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        super.onDestroyView();
//    }
//
//
//    private void initUrl() {
//        if (wapurl == null || wapurl.equals("")) {
//            BasisApp.showToast("网页地址不存在");
//        }
//
////        if (!TextUtils.isEmpty(title)) {
////            setTitle(title);
////        } else {
////            setTitle("");
////        }
//        // myProgressDialog.show();
//        mWebView.loadUrl(wapurl);
//    }
//
//
//
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        // TODO Auto-generated method stub
//        if (mWebView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
//                && event.getRepeatCount() == 0) {
//            mWebView.goBack();
//            return true;
//        }
//
//        return false;
//    }
//
//    private Handler mHandler = new Handler();
//
//    @SuppressLint("NewApi")
//    class MyWebViewClient extends com.tencent.smtt.sdk.WebViewClient {
//        String loginCookie;
//
//        @Override
//        public boolean shouldOverrideUrlLoading(com.tencent.smtt.sdk.WebView view, String url) {
//            // TODO Auto-generated method stub
//            // if(myProgressDialog != null &&
//            // !myProgressDialog.isShowing())myProgressDialog.show();
//            if (url.startsWith("mailto:") || url.startsWith("geo:")
//                    || url.startsWith("tel:") || url.indexOf(".3gp") != -1 || url.indexOf(".mp4") != -1
//                    || url.indexOf(".flv") != -1
//                    || url.indexOf(".swf") != -1) {
//                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
//            } else {
//                mWebView.loadUrl(url);
//            }
//            return true;
//        }
//
//        @Override
//        public void onLoadResource(com.tencent.smtt.sdk.WebView view, String url) {
//            // TODO Auto-generated method stub
//            // CookieManager cookieManager = CookieManager.getInstance();
//            // loginCookie = cookieManager.getCookie(url);
//            super.onLoadResource(view, url);
//        }
//
//        @Override
//        public void onPageFinished(com.tencent.smtt.sdk.WebView view, String url) {
//            // TODO Auto-generated method stub
//            // CookieManager cookieManager = CookieManager.getInstance();
//            // cookieManager.setCookie(url, loginCookie);
//            super.onPageFinished(view, url);
//            dismissProgress();
//        }
//
//        @Override
//        public void onPageStarted(com.tencent.smtt.sdk.WebView view, String url, Bitmap favicon) {
//            // TODO Auto-generated method stub
//            super.onPageStarted(view, url, favicon);
//            if (!getActivity().isFinishing()) {
//                showProgress();
//            }
//        }
//
//    }
//
//    private com.tencent.smtt.sdk.WebChromeClient chromeClient = new com.tencent.smtt.sdk.WebChromeClient() {
//
//        @Override
//        public boolean onJsConfirm(com.tencent.smtt.sdk.WebView arg0, String arg1, String arg2, com.tencent.smtt.export.external.interfaces.JsResult arg3) {
//            return super.onJsConfirm(arg0, arg1, arg2, arg3);
//        }
//
//        View myVideoView;
//        View myNormalView;
//        IX5WebChromeClient.CustomViewCallback callback;
//
//        ///////////////////////////////////////////////////////////
//        //  `
//
//        /**
//         * 全屏播放配置
//         */
//        @Override
//        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
//            View normalView =  findViewById(R.id.webview);
//            ViewGroup viewGroup = (ViewGroup) normalView.getParent();
//            viewGroup.removeView(normalView);
//            viewGroup.addView(view);
//            myVideoView = view;
//            myNormalView = normalView;
//            callback = customViewCallback;
//        }
//
//        @Override
//        public void onHideCustomView() {
//            if (callback != null) {
//                callback.onCustomViewHidden();
//                callback = null;
//            }
//            if (myVideoView != null) {
//                ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
//                viewGroup.removeView(myVideoView);
//                viewGroup.addView(myNormalView);
//            }
//        }
//
//        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//           uploadFile = uploadMsg;
//            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("*/*");
//            startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER);
//        }
//
//        public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
//           uploadFile = uploadMsg;
//            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("*/*");
//            startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER);
//        }
//
//        @Override
//        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String captureType) {
//            LogUtil.i("openFileChooser--->");
//           uploadFile = uploadFile;
//            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("*/*");
//            startActivityForResult(Intent.createChooser(i, "选择文件"),
//                    FILE_CHOOSER);
//            super.openFileChooser(uploadFile, acceptType, captureType);
//        }
//
//        // For Android 5.0+
//        public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView, ValueCallback<Uri[]> filePathCallback, com.tencent.smtt.sdk.WebChromeClient.FileChooserParams fileChooserParams) {
//            LogUtil.i("openFileChooser--5.0->");
//            mUploadCallbackAboveL = filePathCallback;
//            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("*/*");
//            startActivityForResult(
//                    Intent.createChooser(i, "选择文件"),
//                    FILE_CHOOSER);
//            return true;
//        }
//
//        @Override
//        public void onReceivedTitle(com.tencent.smtt.sdk.WebView arg0, final String arg1) {
//            super.onReceivedTitle(arg0, arg1);
////            Log.i("yuanhaizhou", "webpage title is " + arg1);
//
//        }
//    };
//
//    private ValueCallback<Uri> uploadFile;
//    ValueCallback<Uri[]> mUploadCallbackAboveL;
//    private static final int FILE_CHOOSER = 22;
//
//    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
//        if (requestCode != FILE_CHOOSER
//                || mUploadCallbackAboveL == null) {
//            return;
//        }
//        LogUtil.i("onActivityResultAboveL-------->"+resultCode);
//        Uri[] results =  null;
//        if (resultCode == Activity.RESULT_OK) {
//            if (data == null) {
//            } else {
//                String dataString = data.getDataString();
//                ClipData clipData = data.getClipData();
//                if (clipData != null) {
//                    results = new Uri[clipData.getItemCount()];
//                    for (int i = 0; i < clipData.getItemCount(); i++) {
//                        ClipData.Item item = clipData.getItemAt(i);
//                        results[i] = item.getUri();
//                    }
//                }
//                if (dataString != null)
//                    results = new Uri[]{Uri.parse(dataString)};
//            }
//        }
//        mUploadCallbackAboveL.onReceiveValue(results);
//        mUploadCallbackAboveL = null;
//        return;
//    }
//
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.base_btn_back:
//
//                finish();
//                break;
//        }
//    }
//
//}
